package com.example.index.matrix

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.util.Log
import android.view.ScaleGestureDetector
import android.view.View
import com.example.index.R


class MatrixView : View {

    val TAG = "MatrixView"

    var userMatrix = Matrix()

    var invertMatrix = Matrix()

    var scaleGestureDetector: ScaleGestureDetector

    var bitmap: Bitmap

    lateinit var paint: Paint

    constructor(context: Context?) : this(context, null)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {

        val typeArray = context?.obtainStyledAttributes(attrs, R.styleable.MatrixView)
        bitmap = BitmapFactory.decodeResource(
            resources,
            typeArray?.getResourceId(R.styleable.MatrixView_image, R.drawable.xm9) ?: R.drawable.xm9
        )

        typeArray?.recycle()

        paint = Paint(Paint.ANTI_ALIAS_FLAG)
        paint.style = Paint.Style.FILL_AND_STROKE

        scaleGestureDetector = ScaleGestureDetector(context, scaleListener)
    }


    var scaleListener = object : ScaleGestureDetector.SimpleOnScaleGestureListener() {

        override fun onScale(detector: ScaleGestureDetector): Boolean {
            val scaleFactor = detector.scaleFactor

            val fx = detector.focusX
            val fy = detector.focusY

            return true
        }

    }


    var initScale = 1f
    var initTranslateX = 0f
    var initTranslateY = 0f

    /**
     * 把图片缩放到 一定比例可以完整居中显示
     */
    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        Log.i(TAG, "onSizeChanged: ")
        super.onSizeChanged(w, h, oldw, oldh)
        val bw = bitmap.width
        val bh = bitmap.height

        if (bw.toFloat() / bh > w.toFloat() / h) {//宽度大，宽方向缩小到 屏幕尺寸内
            initScale = w.toFloat() / bw
            initTranslateX = 0f
            initTranslateY = (h - bh * initScale) / 2f
        } else { //高度超出，高方向缩小 到屏幕尺寸内
            initScale = h.toFloat() / bh
            initTranslateY = 0f
            initTranslateX = (w - bw * initScale) / 2f
        }
    }


    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        Log.i(TAG, "onDraw: ")


        //translate scale 之后即以后的坐标系
        canvas.translate(initTranslateX, initTranslateY)
        canvas.scale(initScale, initScale)


        canvas.save()

        canvas.concat(userMatrix)
        //记录变化之后的坐标系，为下一次变化提供参照
        canvas.matrix.invert(invertMatrix)
        canvas.restore()


        canvas.drawBitmap(bitmap, 0f, 0f, paint)

    }
}